package top.hmtools.wxmp.core.httpclient.responseHandler;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用于进行回调的处理http response 
 * <br>字符串
 * @author HyboWork
 *
 */
public class ResponseHandlerString implements ResponseHandler<String> {
	
	private final Logger logger = LoggerFactory.getLogger(ResponseHandlerString.class);

	@Override
	public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		InputStream contentInStream = response.getEntity().getContent();
		String contentStr = IOUtils.toString(contentInStream,"UTF-8");
		
		if(this.logger.isDebugEnabled()){
			this.logger.debug("http请求获取的响应状态码是：{}，原文内容是：{}",statusCode,contentStr);
		}
		if(statusCode >= 200 && statusCode <300){
			return contentStr;
		}else{
			throw new RuntimeException("http请求失败，响应状态码是："+statusCode+"，反馈的错误信息是："+contentStr);
		}
	}

}
